/*
	Assignment 4b : Reader and writer using mutex 
	Name : Rushikeh Mukund Fanse
	Roll No : 16
	Div : H 
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<pthread.h>
#include<unistd.h>
using namespace std;
pthread_mutex_t rc_mutex,w_mutex;
int rc;
void *reader_lock(int t)
{
	printf("reader %d is trying to enter\n",t);
	pthread_mutex_lock(&rc_mutex);
	rc++;
	printf("reader %d inside the library\n",t);
	if(rc==1)
	{
		printf("readers reading the book\n");
		pthread_mutex_lock(&w_mutex);
	}
	pthread_mutex_unlock(&rc_mutex);
}
void *reader_unlock(int t)
{
	pthread_mutex_lock(&rc_mutex);
	rc--;
	printf("reader %d left the library\n",t);
	if(rc==0)
	{	
		printf("no readers reading the book\n");
		pthread_mutex_unlock(&w_mutex);	
	}
	pthread_mutex_unlock(&rc_mutex);
}
void *writer_lock()
{
	printf("----------------------writer is trying to enter in library\n");
	pthread_mutex_lock(&w_mutex);
	printf("----------------------writers is writing the book\n");
}	
void *writer_unlock()
{
	pthread_mutex_unlock(&w_mutex);
	printf("----------------------writer is done writing he leaves\n");
}
void *reader(void*i)
{	
	int tid;
	tid=(long)i;
	reader_lock(tid);
	sleep(2);
	reader_unlock(tid);	
}
void *writer(void*)
{
	writer_lock();
	sleep(2);
	writer_unlock();
}
int main()
{
	pthread_t t1[5],t2;
	int i,j=1;
	pthread_mutex_init(&rc_mutex,NULL);
	pthread_mutex_init(&w_mutex,NULL);
	for(i=0;i<5;i++)
		pthread_create(&t1[i],NULL,reader,(void*)(intptr_t)i);
	pthread_create(&t2,NULL,writer,NULL);
	for(i=0;i<5;i++)	
		pthread_join(t1[i],NULL);
	pthread_join(t2,NULL);
	pthread_mutex_destroy(&rc_mutex);
	pthread_mutex_destroy(&w_mutex);
	return 0;
}
/*
rishi@rishi-PC:~$ ./a.out
reader 1 is trying to enter
reader 2 is trying to enter
reader 0 is trying to enter
reader 3 is trying to enter
reader 4 is trying to enter
reader 1 inside the library
readers reading the book
----------------------writer is trying to enter in library
reader 2 inside the library
reader 0 inside the library
reader 3 inside the library
reader 4 inside the library
reader 1 left the library
reader 2 left the library
reader 3 left the library
reader 4 left the library
reader 0 left the library
no readers reading the book
----------------------writers is writing the book
----------------------writer is done writing he leaves

*/
